package io.github.wppli.domain.pay.job;

import com.alibaba.fastjson2.JSONObject;
import io.github.wppli.domain.pay.event.OrderMessageEvent;
import io.github.wppli.domain.pay.model.entity.PaymentData;
import io.github.wppli.domain.pay.service.IOrderService;
import io.github.wppli.domain.pay.util.HttpUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author li--jiaqiang 2025−03−20
 */
@Slf4j
@Component
@AllArgsConstructor
public class NoPayNotifyOrderJob {

    @Resource
    private IOrderService orderService;

    @Resource
    private HttpUtil httpUtil;

    @Resource
    private OrderMessageEvent orderMessageEvent;

    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 每 2min 执行一次
    @Scheduled(cron = "0 */2 * * * ?")
    public void exec() {
        try {
            List<String> orderIds = orderService.queryNoPayNotifyOrder();
            if (orderIds.isEmpty()) {
                log.info("定时任务，订单支付状态更新，暂无未更新订单 NoPayNotify orderIds is null");
                return;
            }
            for (String orderId : orderIds) {
                String data = httpUtil.queryOrderStatusRequest(orderId);
                PaymentData paymentData = JSONObject.parseObject(data, PaymentData.class);
                if (paymentData.getCode() == 1) {
                    // 失败
                    log.error("定时任务，订单支付状态更新失败，订单号：{} error: {}", orderId, paymentData.getMsg());
                    Thread.sleep(6000);
                    continue;
                }
                // 查询成功
                PaymentData.PayData payData = paymentData.getData();
                System.out.println(JSONObject.toJSONString(payData));
                if (payData.getPayStatus() == 0) {
                    log.info("定时任务，订单支付状态更新，当前订单未支付 orderId is {}", orderId);
                    Thread.sleep(6000);
                    continue;
                }
                // 成功支付
                boolean payStatus = orderService.changeOrderPaySuccess(orderId, payData.getPayNo(), payData.getTotalFee(), dateFormat.parse(payData.getSuccessTime()));
                if (!payStatus) {
                    log.error("定时任务，订单支付状态更新失败，订单号：{}", orderId);
                }
                log.info("定时任务，订单支付状态更新，当前订单已支付 orderId is {}", orderId);
                Thread.sleep(6000);
            }
        } catch (Exception e) {
            log.error("定时任务，订单支付状态更新失败", e);
        }
    }
}